﻿using JGSY.CourseManagement.Domain.Entities;
using JGSY.CourseManagement.Infrastructure.Data.Repositories;
using System.Collections.ObjectModel;
namespace JGSY.CourseManagement.Presentation.WpfApp.ViewModels
{
    public class FirstPageViewModel : NotifyPropertyChangedVM
    {
        private int _instrumentValue = 0;

        public int InstrumentValue
        {
            get { return _instrumentValue; }
            set { _instrumentValue = value; SetProperty(ref _instrumentValue,value); }
        }

        private int _itemCount;

        public int ItemCount
        {
            get { return _itemCount; }
            set { _itemCount = value; SetProperty(ref _instrumentValue, value); }
        }

        public ObservableCollection<CourseSeriesEntity> CourseSeriesList { get; set; } = new ObservableCollection<CourseSeriesEntity>();


        Random random = new Random();
        bool taskSwitch = true;
        List<Task> taskList = new List<Task>();
        public FirstPageViewModel()
        {
            this.RefreshInstrumentValue();

            this.InitCourseSeries();
        }
        private void InitCourseSeries()
        {
            var cList = LocalDataAccess.GetInstance().GetCoursePlayRecord();
            // 处理空序列情况，避免Sequence contains no elements异常
            this.ItemCount = cList.Any() ? cList.Max(c => c.SeriesList.Count) : 0;
            foreach (var item in cList)
                this.CourseSeriesList.Add(item);
        }
        //private void InitCourseSeries()
        //{
        //    var cList = LocalDataAccess.GetInstance().GetCoursePlayRecord();
        //    this.ItemCount = cList.Max(c => c.SeriesList.Count);
        //    foreach (var item in cList)
        //        this.CourseSeriesList.Add(item);
        //}
        private void RefreshInstrumentValue()
        {
            var task = Task.Factory.StartNew(new Action(async () =>
            {
                while (taskSwitch)
                {
                    InstrumentValue = random.Next(Math.Max(this.InstrumentValue - 5, -10), Math.Min(this.InstrumentValue + 5, 90));

                    await Task.Delay(1000);
                }
            }));
            taskList.Add(task);
        }

        public void Dispose()
        {
            try
            {
                taskSwitch = false;
                Task.WaitAll(this.taskList.ToArray());
            }
            catch { }
        }
    }
}
